package com.itheima.reggie.common;


import com.itheima.reggie.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@Slf4j
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class GlobalExceptionHandler {
    /**
     * 异常处理方法
     * @param e
     * @return
     */
    //- 指定捕获的异常类型为 SQLIntegrityConstraintViolationException
    //- 解析异常的提示信息, 获取出是那个值违背了唯一约束
    //- 组装错误信息并返回
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<Employee> exceptionHandler(SQLIntegrityConstraintViolationException e){
        log.info(e.getMessage());
        //判断异常信息是否为用户名重复
        if (e.getMessage().contains("Duplicate entry")) {
            String[] s = e.getMessage().split(" ");
            String msg = s[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知的错误");
    }

    /**
     * 分类异常处理方法
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> CustomException(CustomException e){
        log.info(e.getMessage());
        return R.error(e.getMessage());
    }
}
